// vue2 路由配置
// import VueRouter from 'vue-router'
// const router  = new VueRouter({
//   mode: 'history' // hash history,
//   routes: [
//     { path: '/home', component: () => import('@/views/Home/index.vue')}
//   ]
// })
// export default router
// vue3 路由配置
import { useUserStore } from '@/stores'
import { createRouter, createWebHistory, routerKey } from 'vue-router'
// 引入 NProgress 及其样式
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // history: createWebHashHistory(),
  routes: [
    { path: '/login', component: () => import('@/views/Login/index.vue'), meta: { title: '登录' } },
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: 'home',
          component: () => import('@/views/Home/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: 'article',
          component: () => import('@/views/Article/index.vue'),
          meta: { title: '健康百科' }
        },
        {
          path: 'notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: { title: '消息通知' }
        },
        { path: 'user', component: () => import('@/views/User/index.vue'), meta: { title: '我的' } }
      ]
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue'),
      meta: { title: '家庭档案' }
    }
  ]
})
// 关闭 NProgress 的 loading 效果
NProgress.configure({
  showSpinner: false
})

// 跳转路由前，开启进度条
router.beforeEach((to) => {
  NProgress.start()
})
// 全局前置守卫
router.beforeEach((to, from) => {
  // 获取用户仓库
  const userStore = useUserStore()
  const whiteList = ['/login']
  // 没登录,去的页面不是login,跳转到login
  if (!userStore.user?.token && !whiteList.includes(to.path)) return '/login'
  // return
})

// 全局后置守卫
router.afterEach((to) => {
  // 设置页面标题
  document.title = `优医问诊-${to.meta.title || ''}`
  // 关闭进度条
  NProgress.done()
})

export default router
